package api

import (
	"openapi.itspire.cn/common/dict"
	"openapi.itspire.cn/common/throw"
	"openapi.itspire.cn/database"
	"openapi.itspire.cn/model"
	"openapi.itspire.cn/service/baidumap"
	"openapi.itspire.cn/utils"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"time"
)

func VisitCreate(c *gin.Context) {
	var visit model.Visit

	if err := c.ShouldBindJSON(&visit); err != nil {
		throw.ParameterError(c, err.Error())
		return
	}

	ip, _ := utils.Ip2Long(c.ClientIP())
	if ip != 0 {
		country, province, city := baidumap.GetIpLookup(c.ClientIP())
		visit.Country = country
		visit.Province = province
		visit.City = city
	}
	visit.Ip = ip
	visit.CreateTime = uint64(time.Now().Unix())
	res3 := database.Ins.NewRecord(visit)
	if res3 {
		if err := database.Ins.Create(&visit).Error; err != nil {
			panic(err)
		}
	}

	if visit.ArticleId > 0 {
		var article model.Article
		database.Ins.Model(&article).
			Where("id = ? AND status = ? AND delete_time = ?", visit.ArticleId, dict.StatusOn, dict.DeleteNot).
			UpdateColumn("reading_num", gorm.Expr("reading_num + ?", 1))
	}

	utils.Success(c, nil)
}
